/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.daily.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.commons.collections.map.LinkedMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.highchart.service.HighChartService;
import ssn.common.util.DateUtil;
import ssn.common.util.Util;
import ssn.common.view.AjaxView;
import ssn.common.view.CommonExcelView;
import ssn.common.vo.WaterConstants;
import ssn.common.web.CommonController;
import ssn.daily.service.DailyService;
import ssn.daily.vo.DailyVO;
import ssn.servicearea.vo.ServiceAreaVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Logrmation  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2009.03.16           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings({"rawtypes","unchecked"})
@Controller
public class DailyController extends CommonController{
	
    @Resource(name = "dailyService")
    private DailyService dailyService;
    
    @Resource(name = "highchartService")
    private HighChartService highchartService;

    
    
    
    /**
	 * 오수/전력 사용
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/daily/waterElect.do")
    public String waterElect(@ModelAttribute("dailyVO") DailyVO dailyVO,
    			ModelMap model) throws Exception {
    	
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		if(EgovStringUtil.isEmpty(dailyVO.getSearchServiceArea())){
    			dailyVO.setSearchServiceArea(getServiceAreaKeyByFirstRow((List)resultOtherInfo.get("serviceareaList")));
    		}
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	List<Map> resultList = dailyService.selectDailyChart(dailyVO);
    	Map resultMap = highchartService.getChart(resultList, 3);
    	
    	model.addAttribute("dailyVO", dailyVO);
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("resultMap", resultMap);
        return "/daily/waterElect";
    }
    
    /**
     * 오수/전력 사용  엑셀 다운
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/daily/waterElectExcelDown.do")
    public ModelAndView waterElectExcelDown(@ModelAttribute("dailyVO") DailyVO dailyVO,
    		ModelMap model) throws Exception {
    	ModelAndView mav = new ModelAndView(new CommonExcelView());
    	String sheetName = "";
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		if(EgovStringUtil.isEmpty(dailyVO.getSearchServiceArea())){
    			dailyVO.setSearchServiceArea(getServiceAreaKeyByFirstRow((List)resultOtherInfo.get("serviceareaList")));
    		}
    		sheetName = Util.getServiceAreaName((List)resultOtherInfo.get("serviceareaList"), dailyVO.getSearchServiceArea());
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    		sheetName = loginSessionInfo.get().getSsa_area_name();
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	
    	List<Map> resultList = dailyService.selectDailyChart(dailyVO);
    	
    	Map resultMap = new HashMap();
    	Map headerName = new LinkedMap();
    	
    	headerName.put("dailyDate", "날짜");
    	headerName.put("areaName", "현장명");
    	headerName.put("iflowDwater", "오수 유입량 (㎥/일)");
    	headerName.put("oflowDwater", "오수 방류량 (㎥/일)");
    	headerName.put("electNumber", "전력 사용량 (kw/일)");
    	resultMap.put("sheetName", sheetName);
    	resultMap.put("fileName", sheetName+"-오수/전력사용량-"+dailyVO.getSearchSdate()+"~"+dailyVO.getSearchEdate()+".xls");
    	resultMap.put("headerName", headerName);
    	resultMap.put("excelList", resultList);
    	mav.addObject("excelMap", resultMap);
    	return mav;
    }
    
    /**
     * 수질현황
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/daily/waterQuality.do")
    public String waterQuality(@ModelAttribute("dailyVO") DailyVO dailyVO,
    		ModelMap model) throws Exception {
    	
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		if(EgovStringUtil.isEmpty(dailyVO.getSearchServiceArea())){
    			dailyVO.setSearchServiceArea(getServiceAreaKeyByFirstRow((List)resultOtherInfo.get("serviceareaList")));
    		}
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	List<Map> resultList = dailyService.selectDailyChart(dailyVO);
    	Map resultMap = highchartService.getChart(resultList, 4);
    	
    	model.addAttribute("dailyVO", dailyVO);
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("resultMap", resultMap);
    	
    	return "/daily/waterQuality";
    }
    
    /**
     * 수질현황  엑셀 다운
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/daily/waterQualityExcelDown.do")
    public ModelAndView waterQualityExcelDown(@ModelAttribute("dailyVO") DailyVO dailyVO,
    		ModelMap model) throws Exception {
    	ModelAndView mav = new ModelAndView(new CommonExcelView());
    	String sheetName = "";
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		if(EgovStringUtil.isEmpty(dailyVO.getSearchServiceArea())){
    			dailyVO.setSearchServiceArea(getServiceAreaKeyByFirstRow((List)resultOtherInfo.get("serviceareaList")));
    		}
    		sheetName = Util.getServiceAreaName((List)resultOtherInfo.get("serviceareaList"), dailyVO.getSearchServiceArea());
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    		sheetName = loginSessionInfo.get().getSsa_area_name();
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	
    	List<Map> resultList = dailyService.selectDailyChart(dailyVO);
    	
    	Map resultMap = new HashMap();
    	Map headerName = new LinkedMap();
    	
    	headerName.put("dailyDate", "날짜");
    	headerName.put("areaName", "현장명");
    	headerName.put("bodNum", "BOD");
    	headerName.put("ssNum", "SS");
    	headerName.put("tnNum", "T-N");
    	headerName.put("tpNum", "T-P");
    	headerName.put("ecNum", "총대장구군");
    	headerName.put("unusualYn", "특이사항유무");
    	headerName.put("unusualCont", "특이사항내용");
    	resultMap.put("sheetName", sheetName);
    	resultMap.put("fileName", sheetName+"-수질현황-"+dailyVO.getSearchSdate()+"~"+dailyVO.getSearchEdate()+".xls");
    	resultMap.put("headerName", headerName);
    	resultMap.put("excelList", resultList);
    	mav.addObject("excelMap", resultMap);
    	return mav;
    }
    
    public String getServiceAreaKeyByFirstRow(List serviceAreaList){
    	if(serviceAreaList == null || serviceAreaList.size() == 0){
    		return "";
    	}
    	return ((ServiceAreaVO)serviceAreaList.get(0)).getSsa_area_key();
    }
    
    /**
     * 슬러지
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/daily/sludge.do")
    public String sludge(@ModelAttribute("dailyVO") DailyVO dailyVO,
    		ModelMap model) throws Exception {
    	
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	List<Map> resultList = dailyService.selectDailySludge(dailyVO);
    	
    	model.addAttribute("dailyVO", dailyVO);
    	model.addAttribute("resultList", resultList);
    	
    	return "/daily/sludge";
    }
    
    /**
     * 슬러지 엑셀 다운
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/daily/sludgeExcelDown.do")
    public ModelAndView sludgeExcelDown(@ModelAttribute("dailyVO") DailyVO dailyVO,
    		ModelMap model) throws Exception {
    	ModelAndView mav = new ModelAndView(new CommonExcelView());
    	String sheetName = "전체";
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		sheetName = Util.getServiceAreaName((List)resultOtherInfo.get("serviceareaList"), dailyVO.getSearchServiceArea());
    	}else{
    		dailyVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    		sheetName = loginSessionInfo.get().getSsa_area_name();
    	}
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchEdate())){
    		dailyVO.setSearchEdate(DateUtil.getCDAsStringYYYY_MM_DD());
    	}
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchSdate())){
    		dailyVO.setSearchSdate(DateUtil.getCalcDateAsStringYyyyMmDd(dailyVO.getSearchEdate(), WaterConstants.SEARCH_DEFAULT_LAST_MONTH, "month"));
    	}
    	List<Map> resultList = dailyService.selectDailySludge(dailyVO);
    	Map resultMap = new HashMap();
    	Map headerName = new LinkedMap();
    	/* 전체일 경우 앞에 현장 표시 */
    	if(EgovStringUtil.isEmpty(dailyVO.getSearchServiceArea())){
    		headerName.put("areaName", "현장명");
    	}
    	headerName.put("dailyDate", "날짜");
    	headerName.put("sludgeVolm", "용량");
    	headerName.put("sludgeComp", "업체명");
    	headerName.put("sludgeCost", "금액");
    	resultMap.put("sheetName", sheetName);
    	resultMap.put("fileName", sheetName+"-슬러지처리현황-"+dailyVO.getSearchSdate()+"~"+dailyVO.getSearchEdate()+".xls");
    	resultMap.put("headerName", headerName);
    	resultMap.put("excelList", resultList);
    	mav.addObject("excelMap", resultMap);
    	return mav;
    }
    
    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/daily/dailyList.do")
    public String dailyList(@ModelAttribute("dailyVO") DailyVO dailyVO,
    			ModelMap model) throws Exception {
    	
    	/** pageUnit : 페이지 리스트 개수, pageSize : 페이징 개수
    	dailyVO.setPageUnit(15);
    	dailyVO.setPageSize(15);
    	*/
    	if(loginSessionInfo.get().isAdmin()){
    		Map resultOtherInfo = dailyService.selectDailyOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    		dailyVO.setSdl_area_key("");
    	}else{
    		dailyVO.setSdl_area_key(loginSessionInfo.get().getSsa_area_key());
    	}
    	Map resultMap = dailyService.selectDailyLogList(dailyVO);
    	List resultList = (List)resultMap.get("resultList");
    	dailyVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("dailyVO", dailyVO);
        
        return "/daily/dailyList";
    }
    
    /**
     * 뷰페이지
     * @param dailyVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/dailyView.do")
    public String dailyView(@ModelAttribute("dailyVO") DailyVO dailyVO,
    			ModelMap model) throws Exception {
    	
    	if(EgovStringUtil.isEmpty(dailyVO.getSdl_dlog_key())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	DailyVO resultVO = dailyService.selectDailyLog(dailyVO);
    	if(resultVO != null){
    		resultVO.setSearchParam(dailyVO);
    	}
    	model.addAttribute("weekAsString", DateUtil.getDayOfWeekAsString(resultVO.getSdl_daily_date()));
    	model.addAttribute("resultVO", resultVO);
        return "/daily/dailyView";
    }
    
    /**
     * 글쓰기 수정폼
     * @param dailyVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/dailyWriteForm.do")
    public String dailyWriteForm(@ModelAttribute("dailyVO") DailyVO dailyVO,
    			ModelMap model) throws Exception {
    	if(EgovStringUtil.isNotEmpty(dailyVO.getSdl_dlog_key())){
    		DailyVO resultVO = dailyService.selectDailyLog(dailyVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(dailyVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    		model.addAttribute("weekAsString", DateUtil.getDayOfWeekAsString(resultVO.getSdl_daily_date()));
    	}else{
    		dailyVO.setSdl_area_key(loginSessionInfo.get().getSsa_area_key());
    		dailyVO.setSdl_daily_date(DateUtil.getCDAsStringYYYY_MM_DD());
    		dailyVO.setInvenVOList(dailyService.selectDailyFirstInven());
    		model.addAttribute("resultVO", dailyService.appendPreData(dailyVO));
    		model.addAttribute("weekAsString", DateUtil.getDayOfWeekAsString(dailyVO.getSdl_daily_date()));
    	}
        return "/daily/dailyWriteForm";
    }
    
    @RequestMapping(value="/daily/dailySave.do", method=RequestMethod.GET)
    public String dailyWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/daily/dailyWriteForm.do";
    }
    
    /**
     * 저장/수정
     * @param dailyVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/dailySave.do", method=RequestMethod.POST)
    public ModelAndView dailySave(@ModelAttribute("dailyVO") @Valid DailyVO dailyVO, BindingResult bindingResult) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/daily/dailyView.do"));
    	if(bindingResult.hasErrors()){
    		for(FieldError error :  bindingResult.getFieldErrors()){
    			mav.addObject("error_"+error.getField(), error.getDefaultMessage());
    		}
    		mav.setViewName("/daily/dailyWriteForm");
    		mav.addObject("resultVO", dailyVO);
			return mav;
    	}
    	if(EgovStringUtil.isNotEmpty(dailyVO.getSdl_dlog_key())){
    		dailyVO.setSdl_modi_id(loginSessionInfo.get().getSsa_login_id());
    		dailyService.updateDailyLog(dailyVO);
    	}else{
    		dailyVO.setSdl_area_key(loginSessionInfo.get().getSsa_area_key());
    		dailyVO.setSdl_regi_id(loginSessionInfo.get().getSsa_login_id());
    		if(EgovStringUtil.isEmpty(dailyVO.getSdl_area_key()))
    			throw new EgovBizException(propertiesService.getString("info.grade.msg"));
    		dailyService.insertDailyLog(dailyVO);
    	}
    	mav.addObject("sdl_dlog_key", dailyVO.getSdl_dlog_key());
    	mav.addObject("pageIndex", dailyVO.getPageIndex());
    	return mav;
    } 
    
    /**
     * 이전 데이터 날짜 변경시 ajax
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/dailyDateChange.do", method=RequestMethod.POST)
    public ModelAndView dailyDateChange(@RequestParam(value="dateId") String dateId) throws Exception {
    	ModelAndView mav = new ModelAndView(new AjaxView());
    	DailyVO dailyVO = new DailyVO();
    	dailyVO.setSdl_daily_date(dateId);
    	dailyVO.setSdl_area_key(loginSessionInfo.get().getSsa_area_key());
    	dailyVO.setInvenVOList(dailyService.selectDailyFirstInven());
    	dailyVO = dailyService.appendPreData(dailyVO);
    	String result = "{\"success\":\"false\"}";
    	StringBuffer sb = new StringBuffer();
    	/**
    	 * vo.setPre_sdl_elect_number("0"); // 전일 전력
			vo.setPre_sdl_iflow_dwater("0"); // 전일 유입량
			vo.setPre_sdl_oflow_dwater("0"); // 전일 방류량
			
			for(InvenVO invenVO : vo.getInvenVOList()){
				invenVO.setPre_sui_total_stock("0");
			}
    	 */
    	sb.append("{");
    	sb.append("\"electNumber\":\""+dailyVO.getPre_sdl_elect_number()+"\",");
    	sb.append("\"iflowDwater\":\""+dailyVO.getPre_sdl_iflow_dwater()+"\",");
    	sb.append("\"oflowDwater\":\""+dailyVO.getPre_sdl_oflow_dwater()+"\",");
    	sb.append("\"inven\":[");
    	for(int i=0; i<dailyVO.getInvenVOList().size();i++){
    		sb.append("{\"invenKey\":\""+dailyVO.getInvenVOList().get(i).getSui_code_key()+"\",");
    		sb.append("\"invenPreTotalStock\":\""+dailyVO.getInvenVOList().get(i).getPre_sui_total_stock()+"\"}");
    		if(i < dailyVO.getInvenVOList().size()-1){
    			sb.append(",");
    		}
    	}
    	sb.append("]");
    	sb.append("}");
    	result = sb.toString(); 
    	mav.addObject("result", result);
    	return mav;
    }
    
    /**
     * 삭제
     * @param dailyVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/dailyUpdate.do", method=RequestMethod.POST)
    public ModelAndView dailyDelete(@ModelAttribute("dailyVO") DailyVO dailyVO) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/daily/dailyView.do"));
    	if(EgovStringUtil.isNotEmpty(dailyVO.getSdl_dlog_key())){
    		dailyVO.setSdl_modi_id(loginSessionInfo.get().getSsa_login_id());
    		dailyService.updateStatusDailyLog(dailyVO);
    	}else{
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	mav.addObject("sdl_dlog_key", dailyVO.getSdl_dlog_key());
    	mav.addObject("pageIndex", dailyVO.getPageIndex());
    	return mav;
    } 
    
    /**
     * 파일 삭제
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/daily/deleteAttachFile.do", method=RequestMethod.POST)
    public ModelAndView deleteAttachFile(@RequestParam(value="sdl_dlog_key") String sdl_dlog_key) throws Exception {
    	ModelAndView mav = new ModelAndView(new AjaxView());
    	String result = "false";
    	if(dailyService.deleteDailyAttachFile(sdl_dlog_key))
    		result = "true";
    	mav.addObject("result", result);
    	return mav;
    }
}
